package com.example.treasure_back.utils;

import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

@Component
public class EmailUtil {
    private static String fromEmail = "1197396802@qq.com";
    private static String password = "yxjohaiootawiajc";
    private static String myEmailSMTPHost = "smtp.qq.com";
    private static Properties props;
    private static Session session;

    public EmailUtil() {
        props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", myEmailSMTPHost);
        props.setProperty("mail.smtp.ssl.enable","true");
        props.setProperty("mail.smtp.post","465");
        props.setProperty("mail.smtp.auth", "true");
        session = Session.getInstance(props);
    }

    public MimeMessage createMimeMessage(String toEmail) throws MessagingException, UnsupportedEncodingException {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromEmail, "验证码发送系统", "UTF-8"));
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(toEmail));
        message.setSubject(toEmail + "的邮箱验证", "UTF-8");
        BufferedImage bufferedImage = new BufferedImage(200, 69, BufferedImage.TYPE_3BYTE_BGR);
        String s = VerifyCode.generateString(4);
        message.setContent(s, "text/html;charset=UTF-8");
        message.setSentDate(new Date());
        message.saveChanges();
        return message;
    }

    public String sendEmail(String toEmail) throws MessagingException, IOException {
        Transport transport = session.getTransport();
        transport.connect(fromEmail,password);
        MimeMessage message = createMimeMessage(toEmail);
        transport.sendMessage(message,message.getAllRecipients());
        transport.close();
        return message.getContent().toString();
    }
}
